package com.voicechat.firstmet.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.SharePhotoLookActivity;
import com.voicechat.firstmet.adapter.SharePhotoAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.SharePhotoBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment
 * @ClassName: SharePhotoChildFragment
 * @Description: 共享秀照--------最新   人气
 * @Author: ljp
 * @CreateDate: 2019/1/15 17:41
 * @Version: 1.0
 */
public class SharePhotoChildFragment extends BaseFragment {
    @BindView(R.id.recycler_list)
    RecyclerView recyclerList;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    private String TAG = "SharePhotoChildFragment";
    private int flag;//0最新 1人气
    private int page;
    private SharePhotoAdapter sharePhotoAdapter;
    private List<SharePhotoBean.PageBean.ListBean> tlist;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String deviceInfo;
    public static SharePhotoChildFragment newInstance(int flag) {
        Bundle args = new Bundle();
        SharePhotoChildFragment fragment = new SharePhotoChildFragment();
        args.putInt("flag", flag);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    protected int loadLayout() {
        return R.layout.fragment_share_photo_new_hot;
    }
    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        flag = getArguments().getInt("flag");
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
    }
    private void initView() {
        page = 1;
        tlist = new ArrayList<>();
        smartRefresh.autoRefresh();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                initHttpData();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initHttpData();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        sharePhotoAdapter = new SharePhotoAdapter(context, tlist, R.layout.item_share_photo,"");
        recyclerList.setLayoutManager(new GridLayoutManager(activity, 2));
        recyclerList.setAdapter(sharePhotoAdapter);
        sharePhotoAdapter.setSetItemClick(new SharePhotoAdapter.SetItemClick() {
            @Override
            public void setLookPhotoItem(int position, SharePhotoBean.PageBean.ListBean listBean) {
                //更新浏览量
                initHttp(listBean);
                if(listBean.getSign() == 0) {
                    showGoldPopu(listBean);
                }else {
                    Intent intent = new Intent(activity, SharePhotoLookActivity.class);
                    intent.putExtra("imageUrl",listBean.getImgUrl());
                    intent.putExtra("time",listBean.getCreateDate());
                    intent.putExtra("id",listBean.getId());
                    startActivity(intent);
                }
            }
        });
        initHttpData();
    }
    /**
     * @method
     * @description 更新浏览量
     * @date: 2019/1/16 14:45
     * @author: ljp
     * @return
     */
    private void initHttp(SharePhotoBean.PageBean.ListBean listBean) {
        FaintService.pageViewSharePicture(mySeleInfo.getId(),token,deviceInfo,listBean.getId()).subscribe(result -> {
            Log.i(TAG, "initHttp: -----result------"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                listBean.setNumber(result.getObject().getNumber());
                sharePhotoAdapter.notifyDataSetChanged();
            }
        },throwable -> {

        });
    }
    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        smartRefresh.autoRefresh();
    }
    /**
     * @return
     * @method
     * @description 查看共享秀照应付金币
     * @date: 2018/11/26 17:55
     * @author: ljp
     */
    private void showGoldPopu(SharePhotoBean.PageBean.ListBean listBean) {
        View view = View.inflate(context, R.layout.popu_gold_layout, null);
        PopUtils.showPopupWindow(activity, view, false);
        ImageView imageClose = view.findViewById(R.id.image_close);
        TextView textView = view.findViewById(R.id.tv_voice_chat);
        TextView textViewConent = view.findViewById(R.id.tv_conent);
        textViewConent.setText("查看此相册您需支付"+listBean.getGold()+"金币");
        textView.setText("确认支付");
        imageClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确认支付
                setPay(listBean);
            }
        });
    }
    /**
    * @method
    * @description 查看相册金币支付
    * @date: 2019/1/16 13:45
    * @author: ljp
    * @return
    */
    private void setPay(SharePhotoBean.PageBean.ListBean listBean) {
      FaintService.paySharePicture(mySeleInfo.getId(),token,deviceInfo,listBean.getId(),listBean.getGold()).subscribe(result -> {
          Log.i(TAG, "setPay: ----------"+result.toString());
          if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                toast_MakeText("支付成功");
                initPayHttp(listBean);//更新支付标记
            }else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_GOLD) {
                toast_MakeText(getResources().getString(R.string.share_photo_gold));
            }else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        },throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }
    /**
    * @method
    * @description 更新支付标记
    * @date: 2019/1/25 10:37
    * @author: ljp
    * @return
    */
    private void initPayHttp(SharePhotoBean.PageBean.ListBean listBean) {
        FaintService.signPaySharePicture(mySeleInfo.getId(),token,deviceInfo,listBean.getId()).subscribe(result -> {
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                Intent intent = new Intent(activity, SharePhotoLookActivity.class);
                intent.putExtra("imageUrl",listBean.getImgUrl());
                intent.putExtra("time",listBean.getCreateDate());
                intent.putExtra("id",listBean.getId());
                startActivity(intent);
                PopUtils.hidePopupWindow();
            }else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        },throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }
    /**
    * @method
    * @description 数据请求
    * @date: 2019/1/16 9:53
    * @author: ljp
    * @return
    */
    private void initHttpData() {
        FaintService.selectSharePicture(mySeleInfo.getId(),token,
                deviceInfo,page,flag).subscribe(sharePhotoBean -> {
            Log.i(TAG, "initHttpData: -------------"+sharePhotoBean.getCode());
            Log.i(TAG, "initHttpData: -------------"+sharePhotoBean.getPage().getList().size());
            if (sharePhotoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = sharePhotoBean.getPage().getCount() / sharePhotoBean.getPage().getPageSize() +
                        (sharePhotoBean.getPage().getCount() % sharePhotoBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (i != 0 && page > i) {//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        tlist.clear();
                        smartRefresh.finishRefresh();
                    }
                    if(sharePhotoBean.getPage().getList() != null) {
                        tlist.addAll(sharePhotoBean.getPage().getList());
                        sharePhotoAdapter.notifyDataSetChanged();
                       // smartRefresh.setVisibility(View.VISIBLE);
                    }else {
                      //  linearLayout.setVisibility(View.VISIBLE);
                    }
                    smartRefresh.finishLoadMore();
                }
            } else if (sharePhotoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(sharePhotoBean.getMsg());
            }
        },throwable -> {
            Log.i(TAG, "initHttpData: -----------"+throwable.toString());
                    toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

}
